package com.leantech.android.browser.views


import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.webkit.WebSettings
import android.webkit.WebView

import com.qmuiteam.qmui.BuildConfig
import com.qmuiteam.qmui.util.QMUIDisplayHelper
import com.qmuiteam.qmui.util.QMUIPackageHelper
import com.qmuiteam.qmui.util.QMUIResHelper
import com.qmuiteam.qmui.widget.webview.QMUIWebView

/**
 * Created by cgspine on 2017/12/5.
 */
@SuppressLint("SetJavaScriptEnabled")
class SimpleWebView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = android.R.attr.webViewStyle
) : QMUIWebView(context, attrs, defStyleAttr) {

    init {
        val webSettings: WebSettings = settings
        webSettings.javaScriptEnabled = true
        webSettings.setSupportZoom(true)
        webSettings.builtInZoomControls = true
        webSettings.defaultTextEncodingName = "UTF-8"
        webSettings.useWideViewPort = true
        webSettings.loadWithOverviewMode = true
        webSettings.domStorageEnabled = true
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE
        webSettings.textZoom = 100
        webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
        val screen: String = QMUIDisplayHelper.getScreenWidth(context)
            .toString() + "x" + QMUIDisplayHelper.getScreenHeight(context)
        val userAgent = ("Feifei/" + QMUIPackageHelper.getAppVersion(context)
                + " (Android; " + Build.VERSION.SDK_INT
                + "; Screen/" + screen + "; Scale/" + QMUIDisplayHelper.getDensity(context) + ")")
        val agent: String = settings.userAgentString
        if (!agent.contains(userAgent)) {
            settings.setUserAgentString("$agent $userAgent")
        }

        // 开启调试
        if (BuildConfig.DEBUG) {
            WebView.setWebContentsDebuggingEnabled(true)
        }
    }

    fun exec(jsCode: String) {
        evaluateJavascript(jsCode, null)
    }

    protected override fun getExtraInsetTop(density: Float): Int {
        return (QMUIResHelper.getAttrDimen(context, com.qmuiteam.qmui.R.attr.qmui_topbar_height) / density).toInt()
    }

}